<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>地图定位</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="less/public.css" type="text/css">
    <script src="./jquery.js" type="text/javascript"></script>
    <script src="http://api.map.baidu.com/api?v=2.0&ak=YG2iv0eCzo1z6YTsau5pgd24"></script>
    <style type="text/css">
        body,
        html {
            width: 100%;
            height: 100%;
            margin: 0;
            font-family: "微软雅黑";
        }

        #map_canvas {
            width: 100%;
            height: 100%;
        }

        #result {
            width: 100%
        }
    </style>
</head>

<body>
<div id="map_canvas"></div>
<div id="result"></div>
</body>
<script>
    var allPoint = [];
    var map = new BMap.Map('map_canvas');
    var count = 0;
    map.enableScrollWheelZoom();
    map.centerAndZoom("南京", 14);

    $(function () {
        $.ajax({
            url: 'http://api.jshrdtz.com/api/register/isLogin',
            type: 'get',
            xhrFields: {
                withCredentials: true
            },
            success: function (res) {
                console.log(res);
                if (res === true) {
                    connectWebSocket()
                } else {
                    alert("您还未登录，请先登录！！");
                    location.href = "http://m.jshrdtz.com"
                }
            }
        })
    });

    function connectWebSocket() {

        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            websocket = new WebSocket("ws://api.jshrdtz.com/websocket");
        } else {
            alert('Not support websocket')
        }


        //连接发生错误的回调方法
        websocket.onerror = function () {
            setMessageInnerHTML("error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function (event) {
            setMessageInnerHTML('{}');
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {
            setMessageInnerHTML(event.data);
        }

        //连接关闭的回调方法
        websocket.onclose = function () {
            setMessageInnerHTML("Loc MSG:" + "关闭连接");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            websocket.close();
        }
    }


    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        var curdata = JSON.parse(innerHTML);
        if ($.isEmptyObject(curdata)) {
            return;
        }
        if ((curdata.code && curdata.code !== 0)) {
            alert(curdata.message);
            return;
        }
        if (curdata.result.length === 0) {
            return;
        }

        $.each(curdata.result, function (index, obj) {
            if (allPoint.length === 0) {
                for (let i = 0; i < curdata.result.length; i++) {
                    allPoint.push([]);
                }
            }
            allPoint[index].push({"lat": obj.lat, "lng": obj.lng, "carNo": obj.carNo});
            if (allPoint[index].length > 2) {
                allPoint[index].shift();
            }
            console.log(allPoint)

        });
//        setMap(allPoint);


        initLine(allPoint);
        setTimeout(function () {
            run();
        }, 1500);
    }


    function setMap(points) {
        $.each(points, function (index, obj) {

            var curpoint = new BMap.Point(obj[0].lng, obj[0].lat);
            var curmarker = new BMap.Marker(curpoint, {
                icon: productIcon()
            });

            var label = new BMap.Label(obj[0].carNo, {offset: new BMap.Size(0, -30)});
            label.setStyle({
                border: "1px solid rgb(204, 204, 204)",
                color: "rgb(0, 0, 0)",
                borderRadius: "10px",
                padding: "5px",
                background: "rgb(255, 255, 255)",
            });
            curmarker.setLabel(label);

            map.addOverlay(curmarker);
        });


    }

    // 百度地图API功能
    var bounds = null;
    var linesPoints = null;

    //    var myIcon = new BMap.Icon("http://lbsyun.baidu.com/jsdemo/img/Mario.png", new BMap.Size(32, 70), {imageOffset: new BMap.Size(0, 0)});
    //汽车点的icon
    function productIcon() {
        return new BMap.Icon('http://developer.baidu.com/map/jsdemo/img/car.png', new BMap.Size(52, 26), {anchor: new BMap.Size(27, 13)})
    }

    function initLine(points) {
        bounds = new Array();
        linesPoints = new Array();
        map.clearOverlays();                                                    // 清空覆盖物
        if(count === 0){
            setMap(allPoint);
            count ++;
        }
        $.each(points, function (index, obj) {
            if (obj[1]) {
                var driving = new BMap.DrivingRoute(map, {onSearchComplete: drawLine});  // 驾车实例,并设置回调
                driving.search(new BMap.Point(obj[0].lng, obj[0].lat), new BMap.Point(obj[1].lng, obj[1].lat))
            }

        })

    }

    function run() {
        for (var m = 0; m < linesPoints.length; m++) {
            var pts = linesPoints[m];
            var len = pts.length;
            var carMk = new BMap.Marker(pts[0], {icon: productIcon()});
            map.addOverlay(carMk);
            resetMkPoint(1, len, pts, carMk)
        }

        function resetMkPoint(i, len, pts, carMk) {
            carMk.setPosition(pts[i]);
            if (i < len) {
                setTimeout(function () {
                    i++;
                    resetMkPoint(i, len, pts, carMk);
                }, 100);
            }
        }

    }

    function drawLine(results) {
        var opacity = 0.45;
        var planObj = results.getPlan(0);
        var b = new Array();
        var addMarkerFun = function (point, imgType, index, title) {
            var url;
            var width;
            var height
            var myIcon;
            // imgType:1的场合，为起点和终点的图；2的场合为车的图形
            if (imgType == 1) {
                url = "http://lbsyun.baidu.com/jsdemo/img/dest_markers.png";
                width = 42;
                height = 34;
                myIcon = new BMap.Icon(url, new BMap.Size(width, height), {
                    offset: new BMap.Size(14, 32),
                    imageOffset: new BMap.Size(0, 0 - index * height)
                });
            } else {
                url = "http://lbsyun.baidu.com/jsdemo/img/trans_icons.png";
                width = 22;
                height = 25;
                var d = 25;
                var cha = 0;
                var jia = 0
                if (index == 2) {
                    d = 21;
                    cha = 5;
                    jia = 1;
                }
                myIcon = new BMap.Icon(url, new BMap.Size(width, d), {
                    offset: new BMap.Size(10, (11 + jia)),
                    imageOffset: new BMap.Size(0, 0 - index * height - cha)
                });
            }

            var marker = new BMap.Marker(point, {icon: myIcon});
            if (title != null && title != "") {
                marker.setTitle(title);
            }
            // 起点和终点放在最上面
            if (imgType == 2) {
                marker.setTop(true);
            }
            map.addOverlay(marker);
        }
        var addPoints = function (points) {
            for (var i = 0; i < points.length; i++) {
                bounds.push(points[i]);
                b.push(points[i]);
            }
        }
        // 绘制驾车步行线路
        for (var i = 0; i < planObj.getNumRoutes(); i++) {
            var route = planObj.getRoute(i);
            if (route.getDistance(false) <= 0) {
                continue;
            }
            addPoints(route.getPath());
            // 驾车线路
            if (route.getRouteType() == BMAP_ROUTE_TYPE_DRIVING) {
                map.addOverlay(new BMap.Polyline(route.getPath(), {
                    strokeColor: "#0030ff",
                    strokeOpacity: opacity,
                    strokeWeight: 6,
                    enableMassClear: true
                }));
            } else {
                // 步行线路有可能为0
                map.addOverlay(new BMap.Polyline(route.getPath(), {
                    strokeColor: "#30a208",
                    strokeOpacity: 0.75,
                    strokeWeight: 4,
                    enableMassClear: true
                }));
            }
        }
//        map.setViewport(bounds);
        // 终点
        addMarkerFun(results.getEnd().point, 2, 1);
        // 开始点
        addMarkerFun(results.getStart().point, 2, 0);
        linesPoints[linesPoints.length] = b;
    }


</script>

</html>